package com.fangzhi;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFPictureData;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.util.CellReference;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class ExcelPhotoExtractor {
    public static void main(String[] args) {
        String excelFilePath = "/Users/edy/yhqx_data/aaa.xlsx";
        String outputDirectory = "/Users/edy/yhqx_data/";

        try (FileInputStream fileInputStream = new FileInputStream(excelFilePath);
             Workbook workbook = new XSSFWorkbook(fileInputStream)) {

            for (int sheetIndex = 0; sheetIndex < workbook.getNumberOfSheets(); sheetIndex++) {
                Sheet sheet = workbook.getSheetAt(sheetIndex);
                int lastRowNum = sheet.getLastRowNum();
                Map<String, byte[]> picMap = new HashMap<>();
                XSSFDrawing drawing = (XSSFDrawing) sheet.createDrawingPatriarch();
                if (drawing!= null) {
                    for (int i = 0; i < drawing.getShapes().size(); i++) {
                        Shape shape = drawing.getShapes().get(i);
                        if (shape instanceof Picture) {
                            Picture picture = (Picture) shape;
                            ClientAnchor anchor = picture.getClientAnchor();
                            PictureData pictureData = picture.getPictureData();
                            CellReference cellReference = new CellReference(anchor.getRow1(), anchor.getCol1());
                            picMap.put(cellReference.formatAsString() + "_sheet" + sheetIndex, pictureData.getData());
                        }
                    }
                }

                int pictureIndex = 1;
                for (Map.Entry<String, byte[]> entry : picMap.entrySet()) {
//                    String extension = "";
//                    if (entry.getValue() instanceof XSSFPictureData) {
//                        XSSFPictureData pictureData = (XSSFPictureData) entry.getValue();
//                        extension = pictureData.suggestFileExtension();
//                    }
                    String outputPath = outputDirectory + "1.png";
                    try (FileOutputStream out = new FileOutputStream(outputPath)) {
                        out.write(entry.getValue());
                    }
                    pictureIndex++;
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}